package com.example.study.plus.mybatis_plus.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.study.plus.mybatis_plus.entity.TokenUser;
import com.example.study.plus.mybatis_plus.mapper.TokenUserMapper;
import com.example.study.plus.mybatis_plus.service.TokenUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 根据用户名username保存token的表 服务实现类
 * </p>
 *
 * @author 路飞4
 * @since 2023-04-15
 */
@Service
@Slf4j
public class TokenUserServiceImpl extends ServiceImpl<TokenUserMapper, TokenUser> implements TokenUserService {

//    @CachePut(cacheNames = "token_user", key = "#userId")
    @Override
    public TokenUser saveVoucher(Long userId,String userName, String token) {
        //旧版的登录，会留下登录记录
//        QueryWrapper<TokenUser> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("username",username);
//        if (baseMapper.exists(queryWrapper)){
//            baseMapper.delete(queryWrapper);
//        }
//        TokenUser tokenUser = new TokenUser();
//        tokenUser.setUsername(username);
//        tokenUser.setToken(token);
//        return baseMapper.insert(tokenUser);
        QueryWrapper<TokenUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        TokenUser tokenUser = new TokenUser();
        if (baseMapper.exists(queryWrapper)) {
            tokenUser = baseMapper.selectOne(queryWrapper);
            tokenUser.setToken(token);
            tokenUser.setUserId(userId);
            baseMapper.update(tokenUser, queryWrapper);
        } else {
//            tokenUser.setUserId(userId);
            tokenUser.setUsername(userName);
            tokenUser.setUserId(userId);
            tokenUser.setToken(token);
            baseMapper.insert(tokenUser);
        }
        return tokenUser;
    }

//    @CacheEvict(cacheNames = "token_user", key = "#token")
    @Override
    public int delVoucher(String token) {
        QueryWrapper<TokenUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token", token);
        return baseMapper.delete(queryWrapper);
    }

//    @Cacheable(cacheNames = "token_user", key = "#userName")
    @Override
    public TokenUser findTokenByUserName(String userName) {
        QueryWrapper<TokenUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        log.info(userName);
        return baseMapper.selectOne(queryWrapper);
    }
}
